const { app, BrowserWindow, ipcMain, dialog } = require('electron/main');
const koffi = require('koffi');
const fs = require('fs')
const path = require('node:path');
const resourcesPath = process.resourcesPath;
// const dllPath = path.resolve(resourcesPath, 'DLL', 'NFCCARD64.dll');

const dllPath = path.join(__dirname, 'DLL', 'NFCCARD64.dll');

console.log('DLL Path:', dllPath);

const lib = koffi.load(dllPath);


const initDevice = lib.func('initDevice', 'str', []);
const callnfc = lib.func('callnfc', 'str', ['str']);

const initRespStr = initDevice();
console.log('InitDevice ->:', initRespStr);

let mainWindow
const Dll_write = (_, data) => {

  const resultStr = callnfc(data);
  console.log('DLL Write ->:', data);
  console.log('DLL Back ->:', resultStr);
  return resultStr;
}



async function getAutoHideMenuBar() {
  let res = await readConfig()
  Log()
  if (res === null) return true
  if (Object.prototype.hasOwnProperty.call(res, 'autoHideMenuBar')) {
    return false;
  } else {
    return true
  }
}
async function createWindow() {

  mainWindow = new BrowserWindow({
    width: 1500,
    height: 1000,
    autoHideMenuBar: await getAutoHideMenuBar(),
    icon: "./icon/256.png",
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile("./index.html");
}

app.whenReady().then(() => {

  ipcMain.handle('writeConfig', (event, params) => {
    return writeConfig(event, params);
  });

  ipcMain.handle('Dll_write', (event, data) => {
    return Dll_write(event, data);
  })

  ipcMain.handle('Http_log', (event, params) => {
    return Http_log(event, params);
  });
  ipcMain.handle('readConfig', readConfig)

  ipcMain.handle('quitApp', quitApp)

  ipcMain.handle('getVersion', getVersion)

  ipcMain.handle('Test_Api', async () => {
    return await testApi();
  });
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});


const configPath = path.join(__dirname, '../Hotelconfig.json');



function writeConfig(_, config) {
  try {
    const dir = path.dirname(configPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`222: ${dir}`);
    }

    let finalConfig = config;

    // 如果配置文件存在且有效，则合并配置
    if (fs.existsSync(configPath)) {
      try {
        const rawData = fs.readFileSync(configPath, 'utf8');
        const existingConfig = JSON.parse(rawData);
        finalConfig = { ...existingConfig, ...config }; // 新配置覆盖旧值
        console.log(`1: ${configPath}`);
      } catch (parseError) {
        console.warn(`2: ${configPath}`);
      }
    } else {
      console.log(`3: ${configPath}`);
    }

    // 写入最终配置
    fs.writeFileSync(configPath, JSON.stringify(finalConfig, null, 2));
    console.log(`写入成功: ${configPath}`);
    return true;
  } catch (err) {
    console.error(`写入失败 ${configPath}:`, err);
    return false;
  }
}

function readConfig() {
  // console.log(`readConfig: ${configPath}`);
  try {
    if (!fs.existsSync(configPath)) {
      // console.warn(`read error: ${configPath}`);
      return null;
    }

    const data = fs.readFileSync(configPath, 'utf8');

    return JSON.parse(data);
  } catch (err) {
    console.error(`Error1 ${configPath} :`, err);
    return null;
  }
}



const http = require('http');


// 请求配置

function testApi() {
  return new Promise((resolve) => {
    const config = readConfig();
    const url = new URL(config.IP);
    console.log(url);
    const options = {
      hostname: url.hostname,
      port: url.port,
      path: '/admin/site/captcha',
      method: 'GET',
      timeout: 5000
    };

    const req = http.request(options, (res) => {
      if (res.statusCode >= 200 && res.statusCode < 400) {
        console.log(`1: ${res.statusCode}`);
        resolve({ status: 'success', code: res.statusCode });
      } else {
        console.log(`2: ${res.statusCode}`);
        resolve({ status: 'error', code: res.statusCode });
      }
      res.destroy();
    });

    req.on('error', (error) => {
      console.error(`3: ${error.message}`);
      resolve({ status: 'error', message: error.message });
    });

    req.on('timeout', () => {
      req.destroy();
      resolve({ status: 'timeout' });
    });

    req.end();
  });
}



function quitApp() {
  app.quit();
}



function getVersion() {
  return app.getVersion();
}


const LogPath = path.join(__dirname, '../log');

function Log() {
  fs.access(LogPath, (accessErr) => {
    if (accessErr) {
      // 目录不存在时创建
      fs.mkdir(LogPath, { recursive: true }, (mkdirErr) => {
        if (mkdirErr) {
          console.error('❌ 1:', mkdirErr.message);
        } else {
          console.log(`✅ 2: ${LogPath}`);
        }
      });
    } else {
      console.log(`ℹ️ 3: ${LogPath}`);
    }
  });
}

const Http_logPath = path.join(__dirname, `../log/DLL/${getCurrentTime()}.log`);
function Http_log(_, data) {

  console.log(`Http_log: ${JSON.stringify(data)}`);
  try {
    const dir = path.dirname(Http_logPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    // 1. 读取现有日志内容
    let logData = {};
    if (fs.existsSync(Http_logPath)) {
      const rawData = fs.readFileSync(Http_logPath, 'utf8');
      console.log(`q123: ${rawData}`);
      
      try {
        logData = JSON.parse(rawData);
    
        
      } catch (e) {
        console.error('日志解析失败，重置日志文件');
      }
    }

    // 2. 添加新条目（使用时间戳作为键）
    const timestamp = data.SendTime;
    logData[timestamp] = {
      cardclass: data.type,
      SendData: data.SendData,
      HttpBack: data.HttpBack
    };

    console.log(logData);
    // 3. 写入更新后的完整日志
    fs.writeFileSync(Http_logPath, JSON.stringify(logData, null, 2));
     console.log(`success: ${Http_logPath}`);
    return true;
  } catch (err) {
    console.error(`error: ${Http_logPath}`, err);
    return false;
  }
}


function getCurrentTime() {
    const now = new Date();
    
    const year = now.getFullYear(); // 获取年份
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份（0-11，需要+1）
    const date = String(now.getDate()).padStart(2, '0'); // 获取日期
    
    return `${year}-${month}-${date}`;
}
